<template>
  <view class="container">
    <view v-if="loading" class="loading">
      <text>加载中...</text>
    </view>
    
    <view v-else-if="product" class="product-detail">
      <!-- 商品基本信息 -->
      <view class="product-info">
        <text class="product-name">{{ product.name }}</text>
        <text class="merchant-name">商家：{{ product.merchantName }}</text>
        <text class="product-attr">{{ product.attribute }}</text>
        <text class="create-time">上架时间：{{ formatTime(product.createTime) }}</text>
      </view>
      
      <!-- 价格信息 -->
      <view class="price-info">
        <text class="price">{{ formatPrice(product.price) }}</text>
        <text class="stock">库存：{{ product.num }}件</text>
      </view>
      
      <!-- 状态 -->
      <view class="status-info">
        <text class="status" :class="{ 'status-on': product.status === 1, 'status-off': product.status === 0 }">
          {{ product.status === 1 ? '在售' : '已下架' }}
        </text>
      </view>
      
      <!-- 购买按钮 -->
      <view class="buy-section">
        <button 
          class="buy-btn" 
          :disabled="!canBuy"
          @click="handleBuy"
        >
          {{ buyBtnText }}
        </button>
      </view>
    </view>
    
    <view v-else class="empty">
      <text class="empty-icon">❌</text>
      <text class="empty-text">商品不存在</text>
    </view>
  </view>
</template>

<script>
import { getProductDetail } from '@/api/product.js'
import { createOrder } from '@/api/order.js'

export default {
  data() {
    return {
      productId: null,
      product: null,
      loading: true
    }
  },
  computed: {
    // 是否可以购买
    canBuy() {
      return this.product && this.product.status === 1 && this.product.num > 0
    },
    
    // 购买按钮文字
    buyBtnText() {
      if (!this.product) return '加载中...'
      if (this.product.status === 0) return '商品已下架'
      if (this.product.num <= 0) return '商品缺货'
      return '立即购买'
    }
  },
  onLoad(options) {
    this.productId = options.id
    if (this.productId) {
      this.loadProductDetail()
    } else {
      this.loading = false
    }
  },
  methods: {
    // 加载商品详情
    async loadProductDetail() {
      try {
        const res = await getProductDetail(this.productId)
        this.product = res.data
      } catch (error) {
        console.error('加载商品详情失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },
    
    // 购买商品
    async handleBuy() {
      if (!this.canBuy) return
      
      try {
        // 显示数量选择弹窗
        const result = await this.showQuantityDialog()
        if (!result.confirm) return
        
        const quantity = result.content
        
        // 检查库存
        if (quantity > this.product.num) {
          uni.showToast({
            title: '库存不足',
            icon: 'none'
          })
          return
        }
        
        uni.showLoading({
          title: '创建订单中...'
        })
        
        // 创建订单
        const orderRes = await createOrder({
          productId: this.product.id,
          num: quantity,
          merchantId: this.product.merchantId
        })
        
        uni.hideLoading()
        
        // 跳转到支付页面
        uni.navigateTo({
          url: `/pages/order/pay?orderId=${orderRes.data.orderId}&amount=${orderRes.data.amount}&pointAmount=${orderRes.data.pointAmount}`
        })
        
      } catch (error) {
        uni.hideLoading()
        console.error('购买失败:', error)
        uni.showToast({
          title: '购买失败',
          icon: 'none'
        })
      }
    },
    
    // 显示数量选择弹窗
    showQuantityDialog() {
      return new Promise((resolve) => {
        uni.showModal({
          title: '选择数量',
          editable: true,
          placeholderText: '请输入购买数量',
          success: (res) => {
            if (res.confirm) {
              const quantity = parseInt(res.content)
              if (quantity && quantity > 0) {
                resolve({ confirm: true, content: quantity })
              } else {
                uni.showToast({
                  title: '请输入有效数量',
                  icon: 'none'
                })
                resolve({ confirm: false })
              }
            } else {
              resolve({ confirm: false })
            }
          }
        })
      })
    },
    
    // 格式化价格
    formatPrice(price) {
      return (price / 100).toFixed(2) + '元'
    },
    
    // 格式化时间
    formatTime(time) {
      if (!time) return ''
      return time.split(' ')[0] // 只显示日期部分
    }
  }
}
</script>

<style scoped>
.container {
  min-height: 100vh;
  background: #f5f5f5;
  padding: 30rpx;
}

.loading, .empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 400rpx;
  color: #999;
}

.empty-icon {
  font-size: 80rpx;
  margin-bottom: 20rpx;
}

.empty-text {
  font-size: 28rpx;
}

.product-detail {
  background: #fff;
  border-radius: 12rpx;
  padding: 40rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.product-info {
  margin-bottom: 30rpx;
}

.product-name {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 20rpx;
  line-height: 1.4;
}

.merchant-name {
  font-size: 28rpx;
  color: #666;
  display: block;
  margin-bottom: 15rpx;
}

.product-attr {
  font-size: 26rpx;
  color: #999;
  display: block;
  margin-bottom: 15rpx;
  line-height: 1.5;
}

.create-time {
  font-size: 24rpx;
  color: #ccc;
  display: block;
}

.price-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx 0;
  border-top: 1rpx solid #f0f0f0;
  border-bottom: 1rpx solid #f0f0f0;
  margin-bottom: 30rpx;
}

.price {
  font-size: 48rpx;
  font-weight: bold;
  color: #ff6b6b;
}

.stock {
  font-size: 28rpx;
  color: #666;
}

.status-info {
  margin-bottom: 40rpx;
}

.status {
  padding: 12rpx 24rpx;
  border-radius: 8rpx;
  font-size: 24rpx;
  font-weight: bold;
}

.status-on {
  background: #e8f5e8;
  color: #52c41a;
}

.status-off {
  background: #fff2e8;
  color: #fa8c16;
}

.buy-section {
  text-align: center;
}

.buy-btn {
  width: 100%;
  height: 90rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #fff;
  font-size: 32rpx;
  font-weight: bold;
  border-radius: 12rpx;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
}

.buy-btn::after {
  border: none;
}

.buy-btn[disabled] {
  background: #ccc;
  color: #999;
  opacity: 0.6;
}
</style>
